<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if(!class_exists('Api_lol')){
    class Api_lol extends CI_Controller {

        protected $_action = '';

        protected $_distance = 325;

        public function __construct(){
            parent::__construct();
            $this->load->model('Apilogmodel','m_api_log');
            $this->load->model('Usermodel','m_user');
            $this->load->model('Appmodel','m_app');
            $this->load->model('Lolcustomermodel','m_customer');
            $this->load->model('configmodel','m_config');
            $this->load->database();

            if(is_string($this->uri->rsegments[2]) && stripos($this->uri->rsegments[2], 'api') === 0) {
                return;
            }
            $info = $this->input->post();
            $this->m_api_log->createApiLog(array(
                'ip_address' => $this->input->ip_address(),
                // 'customer_id' => $this->m_app->getCurrentCustomerId(),
                'request_uri' => $_SERVER['REQUEST_URI'],
                'post_data' => json_encode($info),
                'result_data' => '',
                'api_log_time_create' => NOW,
                // 'terminal' => TERMINAL_WEIXIN,
            ));
        }

        public function __destruct() {
            // $this->session->unset_userdata($this->_action);
            $this->db->close();
        }


        public function initCustomer() {
            $this->validate->setRule('openid','string');
            $this->validate->setRule('openid','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('openid_md5','string');
            $this->validate->setRule('openid_md5','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('nickname','string');
            $this->validate->setRule('nickname','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('sex','integer');
            $this->validate->setRule('sex','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('province','string');
            $this->validate->setRule('province','notnull',false);
            $this->validate->setRule('province','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('city','string');
            $this->validate->setRule('city','notnull',false);
            $this->validate->setRule('city','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('country','string');
            $this->validate->setRule('country','notnull',false);
            $this->validate->setRule('country','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('headimgurl','string');
            $this->validate->setRule('headimgurl','notnull',false);
            $this->validate->setRule('headimgurl','message',$this->lang->line('error_parameter'));
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if(md5($info['openid'].FREEDOM_WAR_SALT) != $info['openid_md5']) {
                $this->response->setDetail('请勿恶意访问!');
                $this->response->responseExit();
            }
            unset($info['openid_md5']);


            
            $info['nickname'] = urlencode($info['nickname']);

            $customer = $this->m_customer->getCustomerByOpenid($info['openid']);
            if(empty($customer)) {
                $info['customer_time_create'] = NOW;
                $customer_id = $this->m_customer->createCustomer($info);
                if($customer_id == 0) {
                    $this->response->setDetail('初始化用户失败！请刷新页面！');
                    $this->response->responseExit();
                }
                $customer = $this->m_customer->getCustomer($customer_id);
            } else if($customer['nickname'] != $info['nickname'] || $customer['headimgurl'] != $info['headimgurl']){
                $info['customer_id'] = $customer['customer_id'];
                $this->m_customer->editCustomer($info);
                $customer = $this->m_customer->getCustomer($info['customer_id']);
            }
            $customer['nickname'] = urldecode($customer['nickname']);

            $this->session->set_userdata('lol_customer',$customer);

            

            $this->response->setSuccess();
            $this->response->setDetail('提交成功!');
            $this->response->setAddon(array(
                'customer' => $customer,
            ));
            $this->response->responseExit();
        }

        public function apply() {
            $customer = $this->session->userdata('lol_customer');
            if(empty($customer)) {
                $this->response->setDetail('初始化用户失败！请刷新页面重试！');
                $this->response->responseExit();
            }


            $this->validate->setRule('customer_apply_score','integer');
            $this->validate->setRule('customer_apply_info','string');
            $this->validate->setRule('customer_name','string');
            $this->validate->setRule('customer_phone','string');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            if($info['customer_apply_score'] < 0 || $info['customer_apply_score'] > 100) {
                $this->response->setDetail('分数错误!');
                $this->response->responseExit();
            }

            if(!preg_match("/^1[0-9]\d{9}$/i", $info['customer_phone'])){
                $this->response->setDetail('请输入正确的手机号码!');
                $this->response->responseExit();
            }

            $total_count = $this->m_customer->getTotalGameCount();
            $lower_score_count = $this->m_customer->getLowerScoreCount($info['customer_apply_score']);
            $percent = $total_count > 0 ? floor($lower_score_count*10000/$total_count)/100 : 100;

            $this->m_customer->editCustomer(array(
                'customer_id' => $customer['customer_id'],
                'customer_apply_info' => $info['customer_apply_info'],
                'customer_apply_score' => $info['customer_apply_score'],
                'customer_name' => $info['customer_name'],
                'customer_phone' => $info['customer_phone'],
                'customer_time_apply' => NOW,
                'customer_apply_status' => STATUS_ACTIVE,
            ));

            $customer = $this->m_customer->getCustomer($customer['customer_id']);
            $customer['nickname'] = urldecode($customer['nickname']);

            $this->session->set_userdata('lol_customer',$customer);
            $this->response->setSuccess();
            $this->response->setDetail('提交成功!');
            $this->response->setAddon(array(
                'customer' => $customer,
                'percent' => $percent,
            ));
            $this->response->responseExit();
        }

    }
    
}